import {defineStore} from 'pinia'
import settings from '@/settings.js'
import {login, logout, getInfo} from '@/api/user'
import {resetRouter} from '@/router/index.js'
import {
  getCookieByKey,
  setCookie,
  clearAllCookies
} from '@/utils/cookies'


export const useUserStore = defineStore({
  id: 'user',
  state: () => ({
    token: getCookieByKey(`${settings.cookiePrefix}token`),
    name: '',
    avatar: '',
    introduction: '',
    roles: [],
    routes: [], // 路由
  }),
  getters: {
    rolesLength: state => state.roles.length,
  },
  actions: {
    // 用户登录成功之后，保存token
    saveToken(data) {
      const {token} = data
      setCookie(`${settings.cookiePrefix}token`, token);
      this.token = token;
    },
    // 设置用户信息
    setUserInfos(data) {
      const {name, avatar, roles} = data
      this.name = name
      this.avatar = avatar
      this.roles = roles
    },
    // 清除用户信息
    clearUserInfos() {
      this.token = ''
      this.name = ''
      this.avatar = ''
      this.roles = []
    },
    // 登录
    login(userInfo) {
      const {username, password} = userInfo
      return new Promise((resolve, reject) => {
        login({username: username.trim(), password: password})
          .then((response) => {
            const {data} = response
            this.saveToken(data)
            resolve()
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    // token 登录
    loginByToken(payload) {
      return new Promise((resolve, reject) => {
        getInfo(payload)
          .then((response) => {
            const {data, code} = response
            if (!data || code !== 200) {
              reject('token登录失败')
            }
            this.setUserInfos(data);
            for (const key in data) {
              setCookie(`${settings.cookiePrefix}${key}`, data[key] || '')
            }
            resolve(data)
          })
          .catch((error) => {
            reject(error)
            this.clearUserInfos();
            clearAllCookies()
          })
      })
    },
    // 获取用户信息
    // getInfo() {
    // },
    // 清空所有登录信息
    resetInfo() {
      return new Promise((resolve) => {
        this.clearUserInfos();
        clearAllCookies()
        resetRouter()
        resolve()
      })
    },
    // 退出
    logout() {
      return new Promise((resolve, reject) => {
        logout(this.token)
          .then(() => {
            this.resetInfo();
            resolve()
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
  },
})
